﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using mvcForum.Core;
using mvcForum.Core.Specifications;
using mvcForum.Core.Interfaces.Data;

namespace mvcForum.Web.Extensions {

	public static class ForumUserExtensions {

		/// <summary>
		/// Method for getting the list of groups a given user belongs to.
		/// </summary>
		/// <param name="user">The given user.</param>
		/// <returns>The list of groups the given user belongs to.</returns>
		public static IEnumerable<Group> Groups(this ForumUser user) {
			// Get the Group repository.
			IRepository<Group> groupRepository = DependencyResolver.Current.GetService<IRepository<Group>>();
			// Get the GroupMember repository.
			IRepository<GroupMember> memberRepository = DependencyResolver.Current.GetService<IRepository<GroupMember>>();

			// Let's get all the group memberships the given user has.
			IEnumerable<GroupMember> memberships = memberRepository.ReadMany(new GroupMemberSpecifications.SpecificUser(user));
			// Return the groups of the memberships.
			return memberships.Select(x => x.Group).Distinct();
		}
	}
}